package com.wenhao.leetcode.medium;

import java.util.Deque;
import java.util.LinkedList;

/**
 *
 * 题目：https://leetcode-cn.com/problems/simplify-path/
 * 简化路径
 *
 * @author Wenhao Tong
 * @Description
 * @create 2021-07-09 9:20
 */
public class LeetCode71 {

    public static void main(String[] args) {
        LeetCode71 leetCode71 = new LeetCode71();
        String s = leetCode71.simplifyPath("/home/..");
        System.out.println(s);
    }

    public String simplifyPath(String path) {
        StringBuilder result = new StringBuilder();
        String[] split = path.split("/");
        Deque<String> stack = new LinkedList<>();
        for (int i = 0;i < split.length;i++) {
            if ("..".equals(split[i])) {
                if (stack.size() > 0) {
                    stack.pop();
                }
            } else if (!("".equals(split[i]) || ".".equals(split[i]))){
                stack.push(split[i]);
            }
        }
        while (stack.size() > 0) {
            result.append("/" + stack.pollLast());
        }
        if (result.length() == 0) {
            return "/";
        }
        return result.toString();
    }

}
